/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package action

import (
	"database/sql"

	"gitee.com/WisdomClassroom/cli/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gorm.io/gorm"
)

func UserCreate() (accountID uint32) {
	var err error

	err = glb.DB.Where("uuid = ?", glb.ClassUUID).First(&models.ClassModel{}).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			glb.Logger.Info("Find ClassModel: record not found")
		} else {
			glb.Logger.Error("Find ClassModel error: " + err.Error())
		}
		return
	}

	user := &models.User{
		Type:      sql.NullInt32{Int32: int32(glb.UserType), Valid: true},
		AccountID: int32(glb.AccountID),
		Name:      sql.NullString{String: glb.Name, Valid: true},
		Gender:    sql.NullInt32{Int32: int32(glb.Gender), Valid: true},
	}
	user.PasswordSalt = sql.NullString{String: user.GenSalt(), Valid: true}
	user.PasswordSSHA = sql.NullString{String: user.ComputePasswordSSHA(core.StringToMD5(core.DefaultPassword)), Valid: true}

	tx := glb.DB.Begin()
	err = tx.Create(user).Error
	if err != nil {
		glb.Logger.Error("Create User error: " + err.Error())
		tx.Rollback()
		return
	}
	tx.Commit()

	return uint32(user.AccountID)
}
